package org.ds.auth;

import java.util.Hashtable;

/**
 * A simple utility class that acts as a "trusted repository" of usernames
 * and password. This is a trivial implementation that is used to demonstrate
 * the usage of JAAS and will probably become obsolete in the future when a
 * real/secure authentication mechanism is implemented.
 * 
 * @author Kartick Suriamoorthy
 */
public class UserDictionary
{
	private static UserDictionary dict = null;
	
	private Hashtable<String, char[]> userTable = null;
	
	// static methods
	public static UserDictionary getInstance()
	{
		if (dict == null)
		{
			dict = new UserDictionary();
		}
		
		return dict;
	}
	
	// public methods
	/**
	 * Validates the username and password against a dictionary of existing
	 * usernames and passwords. Returns true only if the username exists in
	 * the dictionary and the password (mapped to that user) matches the
	 * password that is passed in.
	 */
	public boolean validateUser(String username, char[] password)
	{
		boolean validated = false;
		
		if (username != null)
		{
			char[] testPassword = userTable.get(username);
			
			if (testPassword != null)
			{
				if (password.length == testPassword.length)
				{
					for (int i = 0; i < password.length; i++)
					{
						if (password[i] != testPassword[i])
						{
							break;
						}
						
						// will reach here only when all the password
						// characters match the dictionary password
						validated = true;
					}
				}
			}
		}
		
		return validated;
	}
	
	// private methods
	private UserDictionary()
	{
		userTable = new Hashtable<String, char[]>();
		
		userTable.put("yoda", "Dick.Clark".toCharArray());
		userTable.put("vindu.mace", "Samuel.L.Jackson".toCharArray());
	}

}
